package model

import (
	"fmt"
	orm "website/dao"
)

type Managers struct {
	Model
	Name          string `json:"name" gorm:"not null" form:"name" binding:"required"`
	Phone         string `json:"phone" form:"phone" binding:"required"`
	Email         string `json:"addr" gorm:"not null" form:"email" binding:"required"`
	ReceiveStatus bool   `json:"receive" gorm:"not null" form:"receive_status" binding:"required"`
}

func (m *Managers) CreateManagers() (err error) {
	// 创建后台管理员
	if rows := orm.Easy.Where("name = ? AND phone =? AND Email = ?", m.Name, m.Phone, m.Email).Find(&m).RowsAffected; rows != 0 {
		err = fmt.Errorf("该用户已存在")
		return err
	}
	if err = orm.Easy.Create(&m).Error; err != nil {
		return
	}
	return
}

func (m *Managers) UpdateManagers(id int64) (err error) {
	// 更新后台管理员
	var all []Managers
	if err = orm.Easy.Where("id = ?", id).First(&all).Error; err != nil {
		return
	}
	if err = orm.Easy.Model(&all).Updates(&m).Error; err != nil {
		return
	}
	return
}

func (m Managers) FetchAllManagers() (all []Managers, err error) {
	//获取所有后台管理员
	if err = orm.Easy.Find(&all).Error; err != nil {
		return
	}
	return
}

func (m Managers) FetchSingleManagers(status bool) (allManagers []string, err error) {
	//获取具有接收邮件权限的用户
	var all []Managers
	if err = orm.Easy.Where("receive_status = ?", status).Find(&all).Error; err != nil {
		return
	}
	for _, v := range all{
		allManagers = append(allManagers, v.Email)
	}
	return
}

